package com.ibeeking.found.cop.b.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.common.enums.SyncStatusEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.cop.b.rest.service.IFriendsTagsGroupService;
import com.ibeeking.found.cop.b.rest.service.IFriendsTagsService;
import com.ibeeking.found.cop.b.rest.service.IMqService;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.dos.*;
import com.ibeeking.found.cop.service.common.param.FriendsTagsGroupParam;
import com.ibeeking.found.cop.service.common.param.FriendsTagsParam;
import com.ibeeking.found.cop.service.common.param.MqSyncCopParam;
import com.ibeeking.found.cop.service.common.query.FriendsTagsGroupPageQuery;
import com.ibeeking.found.cop.service.common.query.FriendsTagsGroupQuery;
import com.ibeeking.found.cop.service.common.vo.FriendsTagsGroupVO;
import com.ibeeking.found.cop.service.common.vo.FriendsTagsVO;
import com.ibeeking.found.cop.service.mapper.FriendsTagsGroupMapper;
import com.ibeeking.found.cop.service.mapper.FriendsTagsMapper;
import com.ibeeking.found.id.GenerateId;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.date.DateUtil;
import com.ibeeking.nematos.utils.id.IdGenerator;
import com.ibeeking.nematos.utils.json.JsonUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpBaseResp;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalTagGroupInfo;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalTagGroupList;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName FriendsTagsGroupServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class FriendsTagsGroupServiceImpl extends ServiceImpl<FriendsTagsGroupMapper, FriendsTagsGroupDO> implements IFriendsTagsGroupService {

    @Resource
    private FriendsTagsGroupMapper friendsTagsGroupMapper;

    @Resource
    private FriendsTagsMapper friendsTagsMapper;

    @Resource
    private IFriendsTagsService friendsTagsServiceImpl;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    @Resource
    private IMqService mqServiceImpl;

    @Override
    public List<FriendsTagsGroupVO> list(FriendsTagsGroupQuery query) {
        List<FriendsTagsGroupDO> entityDOS = friendsTagsGroupMapper.selectList(new LambdaQueryWrapper<FriendsTagsGroupDO>()
                .eq(query.getId() != null, FriendsTagsGroupDO::getId, query.getId())
                .eq(StringUtils.isNotBlank(query.getGroupCode()), FriendsTagsGroupDO::getGroupCode, query.getGroupCode())
                .like(StringUtils.isNotBlank(query.getGroupName()), FriendsTagsGroupDO::getGroupName, query.getGroupName())
                .orderByDesc(FriendsTagsGroupDO::getCreateTime)
        );
        List<FriendsTagsGroupVO> entityVOS =JsonUtils.jsonToList(entityDOS, FriendsTagsGroupVO.class);
        if(Collections3.isNotEmpty(entityVOS)){
            entityVOS.stream().forEach(d->{
               d.setSyncStatusDesc(SyncStatusEnum.getName(d.getSyncStatus()));
                d.setStatusDesc(PublishStatusEnum.getName(d.getStatus()));
               Long groupId = d.getId();
               List<FriendsTagsDO> tagsListDOS = friendsTagsMapper.selectList(new LambdaQueryWrapper<FriendsTagsDO>().eq(FriendsTagsDO::getGroupId,groupId));
               if(Collections3.isNotEmpty(tagsListDOS)) {
                   List<FriendsTagsVO> tagsListVOS = JsonUtils.jsonToList(tagsListDOS, FriendsTagsVO.class);
                   d.setTagsList(tagsListVOS);
               }
            });
        }
        return entityVOS;
    }

    @Override
    public Page<FriendsTagsGroupVO> pageList(FriendsTagsGroupPageQuery pageQuery) {
        LambdaQueryWrapper<FriendsTagsGroupDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(pageQuery.getId() != null, FriendsTagsGroupDO::getId, pageQuery.getId())
                .eq(StringUtils.isNotBlank(pageQuery.getGroupCode()), FriendsTagsGroupDO::getGroupCode, pageQuery.getGroupCode())
                .like(StringUtils.isNotBlank(pageQuery.getGroupName()), FriendsTagsGroupDO::getGroupName, pageQuery.getGroupName())
                .orderByDesc(FriendsTagsGroupDO::getCreateTime);
        Page<FriendsTagsGroupDO> entityDOPages = friendsTagsGroupMapper.selectPage(new Page<FriendsTagsGroupDO>(pageQuery.getPageNum(), pageQuery.getPageSize()), wrapper);
        Page<FriendsTagsGroupVO> entityVOPages = BeanUtil.convertPage(entityDOPages, FriendsTagsGroupVO.class);
        if(entityVOPages!=null && entityVOPages.getSize()>0){
            List<FriendsTagsGroupVO> friendsTagsGroupVOS = entityVOPages.getRecords();
            if(Collections3.isNotEmpty(friendsTagsGroupVOS)){
                friendsTagsGroupVOS.stream().forEach(d->{
                    Long groupId = d.getId();
                    d.setSyncStatusDesc(SyncStatusEnum.getName(d.getSyncStatus()));
                    d.setStatusDesc(PublishStatusEnum.getName(d.getStatus()));
                    List<FriendsTagsDO> tagsListDOS = friendsTagsMapper.selectList(new LambdaQueryWrapper<FriendsTagsDO>().eq(FriendsTagsDO::getGroupId,groupId));
                    if(Collections3.isNotEmpty(tagsListDOS)) {
                        List<FriendsTagsVO> tagsListVOS = JsonUtils.jsonToList(tagsListDOS, FriendsTagsVO.class);
                        d.setTagsList(tagsListVOS);
                    }
                });
                entityVOPages.setRecords(friendsTagsGroupVOS);
            }
        }

        return entityVOPages;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(FriendsTagsGroupParam param) {
        FriendsTagsGroupDO groupEntityDO = BeanUtil.convertBean(param, FriendsTagsGroupDO.class);
        Long groupId = GenerateId.generateId();
        groupEntityDO.setId(groupId);
        groupEntityDO.setSort(groupId);
        groupEntityDO.setCreateBy(UserUtils.getUserId());
        groupEntityDO.setCreateTime(LocalDateTime.now());
        groupEntityDO.setModifyTime(LocalDateTime.now());
        List<FriendsTagsParam> friendsTagsParamList = param.getTagsList();
        if(Collections3.isNotEmpty(friendsTagsParamList)){
            List<FriendsTagsDO> friendsTagsDOS = new ArrayList<>();
            for(FriendsTagsParam entityParam: friendsTagsParamList) {
                FriendsTagsDO tagsEntityDO = BeanUtil.convertBean(entityParam, FriendsTagsDO.class);
                Long tagsId = GenerateId.generateId();
                tagsEntityDO.setId(tagsId);
                tagsEntityDO.setGroupId(groupId);
                tagsEntityDO.setCreateBy(UserUtils.getUserId());
                tagsEntityDO.setCreateTime(LocalDateTime.now());
                tagsEntityDO.setModifyTime(LocalDateTime.now());
                tagsEntityDO.setSort(entityParam.getSort());
                tagsEntityDO.setStatus(0);
                tagsEntityDO.setDelStatus(0);
                friendsTagsDOS.add(tagsEntityDO);
            }
            LogUtils.info("=======friendsTagsDOS:{}==========",JsonUtils.toJsonStr(friendsTagsDOS));
            if(Collections3.isNotEmpty(friendsTagsDOS)) {
                friendsTagsMapper.insertBatchSomeColumn(friendsTagsDOS);
            }
        }
        LogUtils.info("=======groupEntityDO:{}==========",JsonUtils.toJsonStr(groupEntityDO));
        return friendsTagsGroupMapper.insert(groupEntityDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean modify(FriendsTagsGroupParam param) {
        if(param != null ) {
            Long groupId= param.getId();
            List<Long> allNeedDeletedTags = new ArrayList<>();
            List<FriendsTagsDO> allNeedInsertTags = new ArrayList<>();
            List<FriendsTagsDO> allNeedUpdateTags = new ArrayList<>();

            List<FriendsTagsParam> newTagsList = param.getTagsList();

            FriendsTagsGroupDO entityDO = BeanUtil.convertBean(param, FriendsTagsGroupDO.class);
            entityDO.setModifyBy(UserUtils.getUserId());
            entityDO.setModifyTime(LocalDateTime.now());
            List<FriendsTagsDO> oldAllTagsList = friendsTagsMapper.selectList(new LambdaQueryWrapper<FriendsTagsDO>().eq(FriendsTagsDO::getGroupId, groupId));
            Map<Long, FriendsTagsDO> oldAllTagsMap = Collections3.isNotEmpty(oldAllTagsList)?oldAllTagsList.parallelStream().collect(Collectors.toMap(FriendsTagsDO::getId, x->x, (o, n) -> o)):null;
            List<Long> allOldTagsIdList =  Collections3.isNotEmpty(oldAllTagsList)?oldAllTagsList.stream().map(FriendsTagsDO::getId).collect(Collectors.toList()):null;
            List<Long> allNewTagsIdList = Collections3.isNotEmpty(newTagsList)?newTagsList.stream().map(FriendsTagsParam::getId).collect(Collectors.toList()):null;
            if(Collections3.isNotEmpty(allOldTagsIdList) && Collections3.isNotEmpty(allNewTagsIdList)){
                HashSet<Long> allOldTagsIdHash = new HashSet<>(allOldTagsIdList);
                HashSet<Long> allNewTagsIdHsh = new HashSet<>(allNewTagsIdList);
                if(allOldTagsIdHash.removeAll(allNewTagsIdHsh)){
                    allNeedDeletedTags = new ArrayList<>(allOldTagsIdHash);
                }
            }
            if (Collections3.isNotEmpty(newTagsList)) {
                for (FriendsTagsParam entityParam : newTagsList) {
                    Long tagsId = entityParam.getId();
                    if(tagsId !=null && oldAllTagsMap.containsKey(tagsId)) {
                        FriendsTagsDO tagsEntityDO = BeanUtil.convertBean(entityParam, FriendsTagsDO.class);
                        tagsEntityDO.setGroupId(groupId);
                        tagsEntityDO.setModifyBy(UserUtils.getUserId());
                        tagsEntityDO.setModifyTime(LocalDateTime.now());
                        tagsEntityDO.setSort(entityParam.getSort());
                        tagsEntityDO.setStatus(0);
                        tagsEntityDO.setDelStatus(0);
                        allNeedUpdateTags.add(tagsEntityDO);
                    }else{
                        FriendsTagsDO tagsEntityDO = new FriendsTagsDO();
                        tagsEntityDO.setId(IdGenerator.getId());
                        tagsEntityDO.setGroupId(groupId);
                        tagsEntityDO.setTagsName(entityParam.getTagsName());
                        tagsEntityDO.setSort(entityParam.getSort());
                        tagsEntityDO.setCreateBy(UserUtils.getUserId());
                        tagsEntityDO.setCreateTime(LocalDateTime.now());
                        tagsEntityDO.setModifyTime(LocalDateTime.now());
                        tagsEntityDO.setSort(entityParam.getSort());
                        tagsEntityDO.setStatus(0);
                        tagsEntityDO.setDelStatus(0);
                        allNeedInsertTags.add(tagsEntityDO);
                    }
                }
            }
            LogUtils.info("=======allNeedDeletedTags:{}==========",JsonUtils.toJsonStr(allNeedDeletedTags));
            if(Collections3.isNotEmpty(allNeedDeletedTags)){
                friendsTagsMapper.delete(new LambdaQueryWrapper<FriendsTagsDO>().in(FriendsTagsDO::getId, allNeedDeletedTags));
            }
            LogUtils.info("=======allNeedInsertTags:{}==========",JsonUtils.toJsonStr(allNeedInsertTags));
            if(Collections3.isNotEmpty(allNeedInsertTags)){
                friendsTagsMapper.insertBatchSomeColumn(allNeedInsertTags);
            }
            LogUtils.info("=======allNeedUpdateTags:{}==========",JsonUtils.toJsonStr(allNeedUpdateTags));
            if(Collections3.isNotEmpty(allNeedUpdateTags)){
                friendsTagsServiceImpl.updateBatch(allNeedUpdateTags);
            }
            LogUtils.info("=======updateById entityDO:{}==========",JsonUtils.toJsonStr(entityDO));
            return friendsTagsGroupMapper.updateById(entityDO) > 0;
        }else{
            return false;
        }
    }

    @Override
    public FriendsTagsGroupVO view(Long id) {
        FriendsTagsGroupDO entityDO = friendsTagsGroupMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        FriendsTagsGroupVO entityVO = BeanUtil.convertBean(entityDO, FriendsTagsGroupVO.class);
        if(entityVO!=null){
            Long groupId = entityVO.getId();
            entityVO.setSyncStatusDesc(SyncStatusEnum.getName(entityVO.getSyncStatus()));
            entityVO.setStatusDesc(PublishStatusEnum.getName(entityVO.getStatus()));
            List<FriendsTagsDO> tagsListDOS = friendsTagsMapper.selectList(new LambdaQueryWrapper<FriendsTagsDO>().eq(FriendsTagsDO::getGroupId,groupId));
            if(Collections3.isNotEmpty(tagsListDOS)) {
                List<FriendsTagsVO> tagsListVOS = JsonUtils.jsonToList(tagsListDOS, FriendsTagsVO.class);
                entityVO.setTagsList(tagsListVOS);
            }
        }
        return entityVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeStatus(Long id, Integer status) {
        FriendsTagsGroupDO groupDO = friendsTagsGroupMapper.selectById(id);
        if(groupDO==null) throw new BusinessException("没有查到相关记录!");
        List<FriendsTagsDO> entityDOS = friendsTagsMapper.selectList(new LambdaQueryWrapper<FriendsTagsDO>().eq(FriendsTagsDO::getGroupId, id));
        if(Collections3.isEmpty(entityDOS)) throw new BusinessException("没有查到相关记录！");
        entityDOS.parallelStream().forEach(d->{
            d.setStatus(status);
            d.setModifyBy(UserUtils.getUserId());
            d.setModifyTime(LocalDateTime.now());
        });
        friendsTagsServiceImpl.updateBatch(entityDOS);
        groupDO.setStatus(status);
        groupDO.setModifyBy(UserUtils.getUserId());
        groupDO.setModifyTime(LocalDateTime.now());
        return friendsTagsGroupMapper.updateById(groupDO) >0;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean del(Long id) {
        FriendsTagsGroupDO entityDO = friendsTagsGroupMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        friendsTagsMapper.delete(new LambdaQueryWrapper<FriendsTagsDO>().eq(FriendsTagsDO::getGroupId, id));
        return friendsTagsGroupMapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateBatchById(List<FriendsTagsGroupDO> entityList){
       Boolean reulst = updateBatchById(entityList);
       return reulst;
    }
    /***
     *
     * 向Mq发送执行指令
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer sendInstructionToMq(Long id, String operType){
        String tenantId = UserUtils.getTenantId();
        MqSyncCopParam mqParam = new MqSyncCopParam();
        mqParam.setTenantId(Long.valueOf(tenantId));
        mqParam.setId(id);
        mqParam.setOperType(operType);
        mqServiceImpl.sendSyncToWxTaskMessage(mqParam);
        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer syncFriendsTagsToWxCp(Integer tenantId,Long id, Boolean deleted){
        FriendsTagsGroupDO entityDO = friendsTagsGroupMapper.selectById(id);
        if(entityDO == null) throw new BusinessException("没有查到相关记录！");
        List<FriendsTagsDO> friendsTagsDOS = friendsTagsMapper.selectList(new LambdaQueryWrapper<FriendsTagsDO>().eq(FriendsTagsDO::getGroupId, id));
        Long tagGroupId = entityDO.getId();
        String groupCode = entityDO.getGroupCode();
        if(Collections3.isEmpty(friendsTagsDOS)) throw new BusinessException("没有查到标签数据，请设置后再同步！");
        WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId.longValue());
        WxCpConfigStorage wxCpConfigStorage = wxCpService.getWxCpConfigStorage();
        if (wxCpConfigStorage == null) {
            throw new BusinessException("获取企微服务失败!");
        }
        Integer agentId = wxCpConfigStorage.getAgentId();

        WxCpExternalContactService wxCpExternalContactService = wxCpService.getExternalContactService();
        if (wxCpExternalContactService == null) throw new BusinessException("获取企微服务外部联系人服务!");
        if(deleted){
            try {
                if(agentId == null) return 0;
                if (StringUtils.isEmpty(groupCode)) return 0;
                String[] groupCodeArray = new String[]{groupCode};
                WxCpBaseResp wxCpBaseResp = wxCpExternalContactService.delCorpTag(null, groupCodeArray);
                if (!wxCpBaseResp.success()) {
                    return 0;
                }
            } catch (WxErrorException ex) {
                return 0;
            }
        }else {
            if(StringUtils.isEmpty(groupCode)) {
                try {
                    WxCpUserExternalTagGroupInfo tagGroupInfo = new WxCpUserExternalTagGroupInfo();
                    WxCpUserExternalTagGroupInfo.TagGroup tagGroup = new WxCpUserExternalTagGroupInfo.TagGroup();
                    tagGroup.setGroupName(entityDO.getGroupName());
                    List<WxCpUserExternalTagGroupInfo.Tag> groupTagList = new ArrayList<>();
                    for(FriendsTagsDO friendsTagsDO: friendsTagsDOS){
                        WxCpUserExternalTagGroupInfo.Tag groupTag = new WxCpUserExternalTagGroupInfo.Tag();
                        groupTag.setName(friendsTagsDO.getTagsName());
                        groupTagList.add(groupTag);
                    }
                    tagGroup.setTag(groupTagList);
                    tagGroupInfo.setTagGroup(tagGroup);
                    WxCpUserExternalTagGroupInfo rtnTagGroupInfo = wxCpExternalContactService.addCorpTag(tagGroupInfo);
                    if(rtnTagGroupInfo.getErrcode() == 0){
                        WxCpUserExternalTagGroupInfo.TagGroup rtnTagGroup = rtnTagGroupInfo.getTagGroup();
                        if(rtnTagGroup!=null) {
                            String rtnGroupCode = rtnTagGroup.getGroupId();
                            List<WxCpUserExternalTagGroupInfo.Tag> groupTags = rtnTagGroup.getTag();
                            if(StringUtils.isNotEmpty(rtnGroupCode)){
                                entityDO.setGroupCode(rtnGroupCode);
                                //entityDO.setSort(rtnTagGroup.getOrder());
                                Long buildTime = rtnTagGroup.getCreateTime();
                                if(buildTime!=null){
                                    entityDO.setBuildTime(DateUtil.longToLocalDateTime(buildTime));
                                }
                                entityDO.setSyncStatus(SyncStatusEnum.SYNC_YES.getValue());
                                entityDO.setModifyTime(LocalDateTime.now());
                            }
                            if(Collections3.isNotEmpty(groupTags)){
                                Map<String, WxCpUserExternalTagGroupInfo.Tag> groupTagMap = groupTags.stream().collect(Collectors.toMap(WxCpUserExternalTagGroupInfo.Tag::getName, x->x, (o, n) -> n));
                                for(FriendsTagsDO friendsTagsDO: friendsTagsDOS){
                                    String tagName =  friendsTagsDO.getTagsName();
                                    if(groupTagMap!=null && groupTagMap.containsKey(tagName)){
                                        WxCpUserExternalTagGroupInfo.Tag rtnTag = groupTagMap.get(tagName);
                                        friendsTagsDO.setTagsCode(rtnTag.getId());
                                        Long buildTime = rtnTag.getCreateTime();
                                        if(buildTime!=null){
                                            friendsTagsDO.setBuildTime(DateUtil.longToLocalDateTime(buildTime));
                                        }
                                        //friendsTagsDO.setSort(rtnTag.getOrder());
                                        friendsTagsDO.setSyncStatus(SyncStatusEnum.SYNC_YES.getValue());
                                        friendsTagsDO.setModifyTime(LocalDateTime.now());
                                    }
                                }
                            }
                        }
                        if(Collections3.isNotEmpty(friendsTagsDOS)){
                            friendsTagsServiceImpl.updateBatch(friendsTagsDOS);
                        }
                        if(entityDO!=null){
                            friendsTagsGroupMapper.updateById(entityDO);
                        }
                        return 1;
                    }else{
                        LogUtils.error("同步企业标签出错" + rtnTagGroupInfo.getErrmsg());
                        return 0;
                    }
                }catch(WxErrorException ex){
                    LogUtils.error("同步企业标签出错" + ex);
                    return 0;
                }
            }else{
                try {
                    String[] groupCodeArray = new String[]{groupCode};
                    WxCpUserExternalTagGroupList wxCpUserExternalTagGroupList = wxCpExternalContactService.getCorpTagList(null,groupCodeArray);
                    if(wxCpUserExternalTagGroupList.success() && wxCpUserExternalTagGroupList!=null){
                        List<String> needDeleteLocalTagCodeList = new ArrayList<>();
                        List<String> needDeleteRemoteTagCodeList =  new ArrayList<>();
                        List<WxCpUserExternalTagGroupList.TagGroup> tagGroupList = wxCpUserExternalTagGroupList.getTagGroupList();
                        if(Collections3.isNotEmpty(tagGroupList)){
                            WxCpUserExternalTagGroupList.TagGroup rtnTagGroup = tagGroupList.get(0);
                            if(rtnTagGroup.getDeleted()){
                                this.getBean().del(tagGroupId);
                            }else{
                                if(!rtnTagGroup.getGroupName().equalsIgnoreCase(entityDO.getGroupName())) {
                                    WxCpBaseResp tagGroupWCpBaseResp = wxCpExternalContactService.editCorpTag(groupCode, entityDO.getGroupName(), null);
                                    if (tagGroupWCpBaseResp.getErrcode() != 0) {
                                        LogUtils.error("同步删除远端企业标签组出错" + tagGroupWCpBaseResp.getErrmsg());
                                        return 0;
                                    }
                                }
                                List<WxCpUserExternalTagGroupList.TagGroup.Tag> rtnTagList = rtnTagGroup.getTag();
                                if(Collections3.isNotEmpty(rtnTagList)) {
                                    List<WxCpUserExternalTagGroupList.TagGroup.Tag> needDeleteLocalTagList = rtnTagList.stream().filter(tag->(tag.getDeleted() == true)).collect(Collectors.toList());
                                    if(Collections3.isNotEmpty(needDeleteLocalTagList)) {
                                        needDeleteLocalTagCodeList = needDeleteLocalTagList.stream().map(WxCpUserExternalTagGroupList.TagGroup.Tag::getId).collect(Collectors.toList());
                                        friendsTagsMapper.delete(new LambdaQueryWrapper<FriendsTagsDO>().in(FriendsTagsDO::getTagsCode, needDeleteLocalTagCodeList));
                                    }
                                    List<WxCpUserExternalTagGroupList.TagGroup.Tag> oldValidTagList = rtnTagList.stream().filter(tag->(tag.getDeleted() == false)).collect(Collectors.toList());
                                    List<String> oldValidTagCodeList = Collections3.isNotEmpty(oldValidTagList)?oldValidTagList.stream().map(WxCpUserExternalTagGroupList.TagGroup.Tag::getId).collect(Collectors.toList()):null;
                                    List<String> newTagCodeAllList = friendsTagsDOS.stream().map(FriendsTagsDO::getTagsCode).collect(Collectors.toList());
                                    List<String> newTagCodeList = newTagCodeAllList.stream().distinct().collect(Collectors.toList());
                                    if(Collections3.isNotEmpty(oldValidTagCodeList) && Collections3.isNotEmpty(newTagCodeList)){
                                        HashSet<String> oldValidTagCodeSet = new HashSet<>(oldValidTagCodeList);
                                        HashSet<String> newTagCodeSet = new HashSet<>(newTagCodeList);
                                        oldValidTagCodeSet.removeAll(newTagCodeSet);
                                        needDeleteRemoteTagCodeList = new ArrayList<>(oldValidTagCodeSet);
                                        if(Collections3.isNotEmpty(needDeleteRemoteTagCodeList)){
                                            String[] needDeleteRemoteTagCodeArray =needDeleteRemoteTagCodeList.toArray(new String[needDeleteRemoteTagCodeList.size()]);
                                            WxCpBaseResp wxCpBaseResp = wxCpExternalContactService.delCorpTag(needDeleteRemoteTagCodeArray, null);
                                            if(wxCpBaseResp.getErrcode() != 0){
                                                LogUtils.error("同步删除远端企业标签出错" + wxCpBaseResp.getErrmsg());
                                                return 0;
                                            }
                                        }
                                    }
                                    List<FriendsTagsDO> needRemoteInsertTagsDOS = friendsTagsDOS.stream().filter(tag->(tag.getTagsCode().isEmpty())).collect(Collectors.toList());
                                    List<FriendsTagsDO> needRemoteUpdateTagsDOS = friendsTagsDOS.stream().filter(tag->(!tag.getTagsCode().isEmpty())).collect(Collectors.toList());
                                    if(Collections3.isNotEmpty(needRemoteInsertTagsDOS)){
                                        WxCpUserExternalTagGroupInfo tagGroupInfo = new WxCpUserExternalTagGroupInfo();
                                        WxCpUserExternalTagGroupInfo.TagGroup tagGroup = new WxCpUserExternalTagGroupInfo.TagGroup();
                                        tagGroup.setGroupId(groupCode);
                                        List<WxCpUserExternalTagGroupInfo.Tag> groupTagList = new ArrayList<>();
                                        for(FriendsTagsDO friendsTagsDO: needRemoteInsertTagsDOS){
                                            WxCpUserExternalTagGroupInfo.Tag groupTag = new WxCpUserExternalTagGroupInfo.Tag();
                                            groupTag.setName(friendsTagsDO.getTagsName());
                                            groupTagList.add(groupTag);
                                        }
                                        tagGroup.setTag(groupTagList);
                                        tagGroupInfo.setTagGroup(tagGroup);
                                        WxCpUserExternalTagGroupInfo rtnTagGroupInfo = wxCpExternalContactService.addCorpTag(tagGroupInfo);
                                        if(rtnTagGroupInfo!=null && rtnTagGroupInfo.success()){
                                            WxCpUserExternalTagGroupInfo.TagGroup rtninsertTagGroup = rtnTagGroupInfo.getTagGroup();
                                            String rtnGroupCode = rtninsertTagGroup.getGroupId();
                                            List<WxCpUserExternalTagGroupInfo.Tag> groupTags = rtninsertTagGroup.getTag();
                                            if(Collections3.isNotEmpty(groupTags)){
                                                Map<String, WxCpUserExternalTagGroupInfo.Tag> groupTagMap = groupTags.stream().collect(Collectors.toMap(WxCpUserExternalTagGroupInfo.Tag::getName, x->x, (o, n) -> n));
                                                for(FriendsTagsDO friendsTagsDO: needRemoteInsertTagsDOS){
                                                    String tagName =  friendsTagsDO.getTagsName();
                                                    if(groupTagMap!=null && groupTagMap.containsKey(tagName)){
                                                        WxCpUserExternalTagGroupInfo.Tag rtnTag = groupTagMap.get(tagName);
                                                        friendsTagsDO.setTagsCode(rtnTag.getId());
                                                        Long buildTime = rtnTag.getCreateTime();
                                                        if(buildTime!=null){
                                                            friendsTagsDO.setBuildTime(DateUtil.longToLocalDateTime(buildTime));
                                                        }
                                                        //friendsTagsDO.setSort(rtnTag.getOrder());
                                                        friendsTagsDO.setSyncStatus(SyncStatusEnum.SYNC_YES.getValue());
                                                        friendsTagsDO.setModifyTime(LocalDateTime.now());
                                                    }
                                                }
                                            }
                                        }
                                        friendsTagsServiceImpl.updateBatch(needRemoteInsertTagsDOS);
                                    }
                                    if(Collections3.isNotEmpty(needRemoteUpdateTagsDOS)){
                                        for(FriendsTagsDO friendsTagsDO: needRemoteInsertTagsDOS) {
                                            WxCpBaseResp tagGroupWCpBaseResp = wxCpExternalContactService.editCorpTag(friendsTagsDO.getTagsCode(), friendsTagsDO.getTagsName(), null);
                                            if (tagGroupWCpBaseResp.getErrcode() != 0) {
                                                LogUtils.error("同步删除远端企业标签组出错" + tagGroupWCpBaseResp.getErrmsg());
                                                return 0;
                                            }
                                        }
                                    }
                                }
                            }

                        }
                        return 1;
                    }else{
                        return 0;
                    }
                }catch(WxErrorException ex){
                    LogUtils.error("同步企业标签出错" + ex);
                    return 0;
                }
            }
        }
        return 1;
    }

    private IFriendsTagsGroupService getBean(){
        return SpringBeanUtil.getBean(FriendsTagsGroupServiceImpl.class);
    }
}
